package cs575.server;

import java.nio.ByteBuffer;

import cs575.common.FantasyMessage;
import cs575.common.OpCodes;
import cs575.common.Parser;
import cs575.server.services.AddPlayer;
import cs575.server.services.GetAllPlayers;
import cs575.server.services.GetPlayer;
import cs575.server.services.UpdatePlayer;

public class ServerParser extends Parser {

	@Override
	public FantasyMessage parseMessage(ByteBuffer bb) {
		FantasyMessage message = new FantasyMessage();
		byte opCode = bb.get();

		message.setOpCode(opCode);

		int messageSize = bb.getInt();

		if (messageSize > 0) {
			byte[] m = new byte[messageSize];
			bb.get(m);
			message.setMessage(m);
		} else {
			message.setMessage(new byte[0]);
		}

		FantasyMessage responseMsg = null;

		if (opCode == OpCodes.ADD_PLAYER) {
			AddPlayer addServer = new AddPlayer();
			addServer.execute(message);
		} else if (opCode == OpCodes.UPDATE_PLAYER) {
			UpdatePlayer up = new UpdatePlayer();
			up.execute(message);
		} else if (opCode == OpCodes.GET_ALL_PLAYERS) {
			GetAllPlayers getAllServer = new GetAllPlayers();
			responseMsg = getAllServer.execute(message);
		} else if (opCode == OpCodes.REQUEST_PLAYER) {
			GetPlayer getPlayer = new GetPlayer();
			responseMsg = getPlayer.execute(message);
		}

		return responseMsg;
	}
}
